package com.ctcemti.mdm.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Copyright © 2018 YouoTech Of China,All Right Reserved.
 *
 * @ProjectName: olm
 * @Description:
 * @version: v1.0.0
 * @author: bxf
 * @date: 2018/11/02 17:01
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 * 2018/11/02     bxf           v1.0.0               修改原因
 */
@Slf4j
public class EncryptUtils {

    /**
     * 加密算法名称
     **/
    private static final String AES = "AES";

    /**
     * 字符集
     **/
    private static final String CHARSET = "UTF-8";

    /**
     * AES加密解密KEY
     **/
    private static final String AES_KEY = "CTCE2018";

    /**
     * 加密
     *
     * @param password
     * @return
     */
    public static String AESEncode(String password) {
        if (null == password || "".equals(password)) {
            return null;
        }
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance(AES);
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            //new SecureRandom(AES_KEY.getBytes())
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(AES_KEY.getBytes());
            keygen.init(128, random);
            //3.产生原始对称密钥
            SecretKey originalKey = keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte[] raw = originalKey.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, AES);
            //6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance(AES);
            //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byteEncode = password.getBytes(CHARSET);
            //byte [] byteEncode = parseHexStr2Byte(password);
            //9.根据密码器的初始化方式--加密：将数据加密
            byte[] byteAes = cipher.doFinal(byteEncode);
            //10.将加密后的数据转换为字符串
            //这里用Base64Encoder中会找不到包
            //解决办法：
            //在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
            //11.将字符串返回
            //String content = new BASE64Encoder().encode(byteAes);
            return parseByte2HexStr(byteAes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("加密出错" + e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @return
     */
    public static String AESDecode(String content) {
        if (null == content || "".equals(content)) {
            return null;
        }
        log.info("密码解密，解密前" + content);
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance(AES);
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            //
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(AES_KEY.getBytes());
            keygen.init(128, random);
            //3.产生原始对称密钥
            SecretKey originalKey = keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte[] raw = originalKey.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, AES);
            //6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance(AES);
            //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);
            //8.将加密并编码后的内容解码成字节数组
            //byte [] byteContent = new BASE64Decoder().decodeBuffer(content);
            byte[] byteContent = parseHexStr2Byte(content);
            /*
             * 解密
             */
            byte[] byteDecode = cipher.doFinal(byteContent);
            String aesDecode = new String(byteDecode, CHARSET);
            //String aesDecode = parseByte2HexStr(byteDecode);
            log.info("密码解密，解密后" + aesDecode);
            return aesDecode;
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException
                | BadPaddingException | IllegalBlockSizeException e) {
            e.printStackTrace();
            log.error("解密出错" + e);
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     * @method parseByte2HexStr
     * @since v1.0
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aBuf : buf) {
            String hex = Integer.toHexString(aBuf & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     * @method parseHexStr2Byte
     * @since v1.0
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
